<?php
/* This file is part of LlamaSlayers Ajax Chat
 *
 * The source code is released under the GNU GPL free software license, version 3.
 * Updates can be found at http://llamaslayers-ajax-chat.googlecode.com/
 */

header( 'Content-Type: text/plain' );

require_once dirname( __FILE__ ) . '/config.php';

if ( !empty( $_SERVER['REMOTE_ADDR'] ) ) { // Allow this file to be run as a cron job
	session_start();

	if ( empty( $_SESSION['authenticated'] ) ) // Admins must be logged in. (Duh)
		die( 'The cleanup command can only be initiated by chat administrators' );

	$user = file( dirname( __FILE__ ) . '/db/user/' . $_SESSION['authenticated'] . '.txt' );

	if ( !((int)$user[1] & 2) ) // Require permission 2
		die( 'The cleanup command can only be initiated by chat administrators' );
}

set_time_limit( 0 ); // There might be a lot of chatrooms we need to delete.

$chats = glob( dirname( __FILE__ ) . '/db/chat/*.txt' ); // Get all the chatrooms

foreach ( $chats as $chat ) {
	if ( ( filesize( $chat ) <= 1 || // Chat must be empty or:
		 ( filemtime( $chat ) < time() - TIMEOUT_MESSAGE && // Not used for X seconds
		fileatime( $chat ) < time() - TIMEOUT_VISITED ) ) && // Not visited for X seconds
		basename( $chat ) != 'public.txt' ) { // And it can't be the #public chat.

		file_put_contents( $chat, '-' ); // Unlock the chat file
		file_put_contents( dirname( __FILE__ ) . '/db/online/' . basename( $chat ), '-' ); // Unlock the users file
		usleep( 10000 ); // Wait 10ms
		unlink( $chat ); // Delete the chat file
		unlink( dirname( __FILE__ ) . '/db/online/' . basename( $chat ) ); // Delete the users file
		if ( file_exists( $chat ) || file_exists( dirname( __FILE__ ) . '/db/online/' . basename( $chat ) ) )
			echo 'Unable to delete #' . substr( basename( $chat ), 0, -4 ) . "\n";
		else
			echo 'Deleted #' . substr( basename( $chat ), 0, -4 ) . "\n";
	} else {
		echo 'Kept #' . substr( basename( $chat ), 0, -4 ) . "\n";
	}
}

?>